function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
var socket = io.connect('http://10.0.0.107:1412');

// on connection to server, ask for user's name with an anonymous callback
socket.on('connect', function() {
    // call the server-side function 'adduser' and send one parameter (value of prompt)
    if (userPseudo === 'undefined') {
        mess = "requied login";
        $('#chat-content').append('<b class="pseudo">SERVER:</b> <span class="message">' + mess + '</span><br>');
    }
    else {
        socket.emit('adduser', userPseudo);
    }
});

// listener, whenever the server emits 'updatechat', this updates the chat body
socket.on('updatechat', function(username, data) {
    var mess = htmlEntities(data);
    $('#chat-content').append('<b>' + username + ':</b> ' + mess + '<br>');
    $('#chat-content').scrollTop($('#chat-content')[0].scrollHeight);
});

// listener, whenever the server emits 'updaterooms', this updates the room the client is in
socket.on('updaterooms', function(rooms, current_room) {
    $('#selectRooms').empty();
    $.each(rooms, function(key, value) {
        $('#selectRooms').append('<option value="' + value + '">' + value + '</option>');
    });
});

function switchRoom(room) {
    socket.emit('switchRoom', room);
}

// on load of page
$(function() {
    // when the client clicks SEND
    var sendMessage = false;
    var timeSend = new Date();
    $('#datasend').click(function() {
        var message = $('#data').val();
        $('#data').val('');
        // tell server to execute 'sendchat' and send along one parameter
        if (message != "") {
            if (sendMessage == true) {
                if (timeSend.getTime() <= ((new Date()).getTime() - 1000)) {
                    socket.emit('sendchat', message);
                    timeSend = new Date();
                    console.log(timeSend.getTime());
                }
                else {
                    mess = "You can't send more than 1 message per second";
                    $('#chat-content').append('<b class="pseudo">SERVER:</b> <span class="message">' + mess + '</span><br>');
                    $('#chat-content').scrollTop($('#conversation')[0].scrollHeight);
                }
            }

            if (sendMessage == false) {
                socket.emit('sendchat', message);
                sendMessage = true;
                timeSend = new Date();
                console.log(timeSend.getTime());

            }
        }
    });

    // when the client hits ENTER on their keyboard
    $('#data').keypress(function(e) {
        if (e.which == 13) {
            //$(this).blur();
            $('#datasend').click();
        }
    });

    $("#selectRooms").change(function() {
        var room = $("#selectRooms").val();
        switchRoom(room);
    });
});
